package com.springsecurity.utils;

import com.springsecurity.mapper.MenuMapper;
import com.springsecurity.pojo.Menu;
import com.springsecurity.pojo.Role;
import jakarta.annotation.Resource;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.Collection;
import java.util.List;

@Component
public class MyFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {
	AntPathMatcher antPathMatcher=new AntPathMatcher();
	@Resource
	MenuMapper menuMapper;
	@Override
	public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
		String requestUrl = ((FilterInvocation) object).getRequestUrl();
		List<Menu> menus = menuMapper.getAllMenus();
		for (Menu menu : menus) {
			if (antPathMatcher.match(menu.getUrl(), requestUrl)) {
				List<Role> roles = menu.getRoles();
				String []roleArr=new String[roles.size()];
				for (int i = 0; i < roles.size(); i++) {
					roleArr[i]=roles.get(i).getName();
				}
				return SecurityConfig.createList(roleArr);
			}
		}
		return null;
	}

	@Override
	public Collection<ConfigAttribute> getAllConfigAttributes() {
		return null;
	}

	@Override
	public boolean supports(Class<?> clazz) {
		return false;
	}
}
